package com.lsz.atm.ui.order;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.common.config.Global;
import com.common.event.CommodityEvent;
import com.common.mvp.BaseMvpActivity;
import com.common.thirdparty.ThirdParty;
import com.common.thirdparty.aiyin.AiYinParty;
import com.lsz.atm.R;
import com.lsz.atm.TemporaryDataUtil;
import com.lsz.atm.db.bean.CommodityBean;
import com.lsz.atm.db.bean.PackageBean;
import com.lsz.atm.db.dao_utils.DaoUtils;
import com.lsz.atm.dialog.ConfirmDialog;
import com.lsz.atm.event.StartOrderEvent;
import com.lsz.atm.json.ATMBean;
import com.lsz.atm.json.OrderBean;
import com.lsz.atm.json.OrderNumberBean;
import com.lsz.atm.json.VIPMemberBean;
import com.lsz.atm.ui.pay.PayActivity;
import com.lsz.atm.ui.pay.PaySuccessActivity;
import com.lsz.atm.viewutil.BigDecimalUtils;
import com.lsz.atm.viewutil.SpannableUtil;
import com.util_code.dialog.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import okhttp3.RequestBody;

public class OrderListActivity extends BaseMvpActivity<OrderView, OrderPresent> implements OrderView, View.OnClickListener {

    @BindView(R.id.ll_take_away)
    LinearLayout llTakeAway;
    @BindView(R.id.ll_dine_in)
    LinearLayout llDineIn;
    @BindView(R.id.tv_order_confirm_hint)
    TextView tvOrderConfirmHint;
    @BindView(R.id.tv_order_update_hint)
    TextView tvOrderUpdateHint;
    @BindView(R.id.tv_total_number)
    TextView tvTotalNumber;
    @BindView(R.id.tv_order_total_amount)
    TextView tvOrderTotalAmount;
    @BindView(R.id.rv_order_list)
    RecyclerView rvOrderList;
    @BindView(R.id.tv_order_cancel)
    TextView tvOrderCancel;
    @BindView(R.id.tv_order_contiune)
    TextView tvOrderContiune;
    @BindView(R.id.tv_to_pay)
    TextView tvToPay;
    @BindView(R.id.tv_order_discount_amount)
    TextView tvOrderDiscountAmount;
    @BindView(R.id.tv_order_pay_before_hint)
    TextView tvOrderPayBeforeHint;

    private OrderAdapter orderAdapter;
    private ConfirmDialog confirmDialog;
    private List<CommodityBean> orderList;
    private String currency;
    private String orderNumber;

    private LoadingDialog loadingDialog;
    private String totalAmount = "0";
    private String discountAmount = "0";
    private String couponPrice;
    private ATMBean atmBean;

    public static void startActivity(Activity activity) {
        ThirdParty.checkIsOpened();
        Intent intent = new Intent(activity, OrderListActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_list;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        llTakeAway.setOnClickListener(this);
        llDineIn.setOnClickListener(this);
        tvOrderCancel.setOnClickListener(this);
        tvOrderContiune.setOnClickListener(this);
        tvToPay.setOnClickListener(this);

        tvOrderDiscountAmount.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvOrderList.setLayoutManager(linearLayoutManager);
        ((SimpleItemAnimator) Objects.requireNonNull(rvOrderList.getItemAnimator())).setSupportsChangeAnimations(false);
        orderAdapter = new OrderAdapter(this);
        rvOrderList.setAdapter(orderAdapter);
        orderAdapter.setItemOnClicklistener(orderItemClicklistener);

        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog();
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        orderList = getOrderList();

        orderNumber = getResources().getString(R.string.order_number);
        currency = getResources().getString(R.string.currency);
        setTotalAmountData();

        orderAdapter.resetData(orderList);
        atmBean = Global.getAtmBean();
        if (TextUtils.equals(atmBean.orderType, ATMBean.PICK_UP)) {
            llTakeAway.setBackgroundColor(getResources().getColor(R.color.c_FABE00));
            llDineIn.setBackgroundColor(getResources().getColor(R.color.app_white));
        } else {
            llDineIn.setBackgroundColor(getResources().getColor(R.color.c_FABE00));
            llTakeAway.setBackgroundColor(getResources().getColor(R.color.app_white));
        }

        getPresenter().getMember("201911251000");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private List<CommodityBean> getOrderList() {
        List<CommodityBean> arrayList = new ArrayList<>();
        List<CommodityBean> beanList = DaoUtils.getCommodityInstance().loadAll();
        for (CommodityBean commodityBean : beanList) {
            if (commodityBean.cSelectNumber > 0) {
                arrayList.add(commodityBean);
            } else {
                DaoUtils.getCommodityInstance().deleteObj(commodityBean);
            }
        }
        return arrayList;
    }

    private OrderAdapter.OrderItemClicklistener orderItemClicklistener = new OrderAdapter.OrderItemClicklistener() {

        @Override
        public void onItemDelete(CommodityBean item) {
            CommodityBean loadById = DaoUtils.getCommodityInstance().loadById(item.randomId);
            if (loadById == null) {
                return;
            }
            loadById.cSelectNumber = loadById.cSelectNumber - 1;
            if (loadById.cSelectNumber > 0) {
                loadById.totalPriceList = BigDecimalUtils.sub(loadById.totalPriceList, loadById.priceSell, 2);
                addAndDeleteCommodity(loadById);
            } else if (loadById.cSelectNumber == 0) {
                orderAdapter.getData().remove(loadById);
                orderAdapter.notifyDataSetChanged();
                if (orderAdapter.getData().size() == 0) {
                    EventBus.getDefault().post(new CommodityEvent(true));
                    finish();
                }
                setTotalAmountData();
            }
        }

        @Override
        public void onItemAdd(CommodityBean item) {
            CommodityBean loadById = DaoUtils.getCommodityInstance().loadById(item.randomId);
            if (loadById == null) {
                return;
            }
            loadById.cSelectNumber = loadById.cSelectNumber + 1;
            if (loadById.cSelectNumber > 0) {
                loadById.totalPriceList = BigDecimalUtils.add(loadById.totalPriceList, loadById.priceSell, 2);
            }
            addAndDeleteCommodity(loadById);
            DaoUtils.getCommodityInstance().updateCommodity(loadById);
        }
    };

    private void addAndDeleteCommodity(CommodityBean loadById) {
        for (int i = 0; i < orderAdapter.getData().size(); i++) {
            CommodityBean commodityBean = orderAdapter.getData().get(i);
            if (commodityBean.randomId == loadById.randomId) {
                commodityBean.cSelectNumber = loadById.cSelectNumber;
                commodityBean.totalPriceList = loadById.totalPriceList;
                orderAdapter.notifyItemChanged(i, commodityBean);
            }
        }
        setTotalAmountData();
    }

    private void setTotalAmountData() {
        String totalA = "0";
        long totalN = 0;
        for (CommodityBean orderBean : orderAdapter.getData().size() == 0 ? orderList : orderAdapter.getData()) {
            totalA = BigDecimalUtils.add(totalA, orderBean.totalPriceList, 2);
            List<PackageBean> packageList = DaoUtils.getPackageInstance().loadPackageByRandomId(orderBean.randomId);
            for (PackageBean packageBean : packageList) {
                String tAmount = TemporaryDataUtil.getTotalAmount(packageBean.commodiTotalPrice, packageBean.commodiTotalPrice, orderBean.cSelectNumber);
                totalA = BigDecimalUtils.add(totalA, tAmount, 2);
            }
            totalN = totalN + orderBean.cSelectNumber;
        }
        totalAmount = totalA;
        Global.setOrderNumber(new OrderNumberBean(totalN + ""));

        String amount = currency + " " + totalA;
        if (!TextUtils.equals(discountAmount, "0") && !TextUtils.isEmpty(couponPrice)) {
            tvOrderPayBeforeHint.setVisibility(View.INVISIBLE);
            tvOrderDiscountAmount.setVisibility(View.VISIBLE);
            tvOrderDiscountAmount.setText(amount);
            String discountAt = BigDecimalUtils.sub(totalA, discountAmount, 2);
            discountAt = currency + " " + (BigDecimalUtils.compare(discountAt, "0") ? discountAt : "0");
            SpannableString textSpannable = SpannableUtil.setTextSpannable(discountAt, 2, discountAt.length());
            tvOrderTotalAmount.setText(textSpannable);
        } else {
            tvOrderPayBeforeHint.setVisibility(View.VISIBLE);
            tvOrderDiscountAmount.setVisibility(View.GONE);
            SpannableString textSpannable = SpannableUtil.setTextSpannable(amount, 2, amount.length());
            tvOrderTotalAmount.setText(textSpannable);
        }

        String format = String.format(orderNumber, totalN);
        tvTotalNumber.setText(format);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_take_away:
                setTakeDine(ATMBean.PICK_UP);
                llTakeAway.setBackgroundColor(getResources().getColor(R.color.c_FABE00));
                llDineIn.setBackgroundColor(getResources().getColor(R.color.app_white));
                break;
            case R.id.ll_dine_in:
                setTakeDine(ATMBean.DINE_IN);
                llDineIn.setBackgroundColor(getResources().getColor(R.color.c_FABE00));
                llTakeAway.setBackgroundColor(getResources().getColor(R.color.app_white));
                break;
            case R.id.tv_order_cancel:
                ConfirmDialog.Builder builder = new ConfirmDialog.Builder(OrderListActivity.this);
                confirmDialog = builder.setContentText("是否取消订单").setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
                    @Override
                    public void click(boolean b) {
                        confirmDialog.dismiss();
                        if (b) {
                            DaoUtils.getCommodityInstance().deleteAll();
                            DaoUtils.getPackageInstance().deleteAll();
                            EventBus.getDefault().post(new StartOrderEvent());
                            finish();
                        }
                    }
                }).create();
                confirmDialog.show();
                break;
            case R.id.tv_order_contiune:
                EventBus.getDefault().post(new CommodityEvent(true));
                finish();
                break;
            case R.id.tv_to_pay:
                List<CommodityBean> commodityList = DaoUtils.getCommodityInstance().loadAll();
                if (!loadingDialog.isVisible()) {
                    loadingDialog.show(getSupportFragmentManager(), "loadingdialog");
                }
//                String member = "201911291001";
                String member = "";
                RequestBody createOrder = TemporaryDataUtil.setCreateOrder(atmBean.storeId, member, atmBean.orderType, totalAmount, commodityList, couponPrice);
                getPresenter().getOrderCreate(createOrder);
                break;
            default:
                break;
        }
    }

    public void setTakeDine(String takeDine) {
        if (atmBean != null) {
            atmBean.orderType = takeDine;
        }
        Global.setAtmBean(atmBean);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(StartOrderEvent event) {
        finish();
    }

    @Override
    public void onOrderSuccess(OrderBean orderBean) {
        if (loadingDialog.isVisible()) {
            loadingDialog.dismissAllowingStateLoss();
        }
        if (TextUtils.isEmpty(orderBean.amountActual) || TextUtils.equals(orderBean.amountActual, "0")) {
            PaySuccessActivity.startActivity(OrderListActivity.this, orderBean, 0);
        } else {
            PayActivity.startActivity(OrderListActivity.this, orderBean);
        }
    }

    @Override
    public void onVIPMember(VIPMemberBean vipMemberBean) {

    }

    @Override
    public void onDisountStart() {
        if (!loadingDialog.isVisible()) {
            loadingDialog.show(getSupportFragmentManager(), "loadingdialog");
        }
    }

    @Override
    public void onDiscountAmount(String discountAmount, String couponPrice) {
        if (loadingDialog.isVisible()) {
            loadingDialog.dismissAllowingStateLoss();
        }
        this.discountAmount = discountAmount;
        this.couponPrice = couponPrice;
        setTotalAmountData();
    }

    @Override
    public void onFail() {
        if (loadingDialog.isVisible()) {
            loadingDialog.dismissAllowingStateLoss();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //键盘事件为back时，不监听
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return super.dispatchKeyEvent(event);
        } else {
            return getPresenter().handleKeyEvent(event);
        }
    }
}
